package com.example.jimanguang.Services.Imp;

import com.alibaba.fastjson.JSONObject;
import com.example.jimanguang.Entity.User;
import com.example.jimanguang.Repositories.UserProjection;
import com.example.jimanguang.Repositories.UserRepository;
import com.example.jimanguang.Repositories.untils.StringUtils;
import com.example.jimanguang.Services.UserService;
import com.example.jimanguang.constants.ApiConstant;
import com.example.jimanguang.constants.Messages;
import com.example.jimanguang.web.models.ApiResult;
import com.example.jimanguang.web.models.VmUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class UserServiceimp implements UserService {
//    @Override注解是一个声明注解，用于指示下面的方法将覆盖超类或接口中具有相同名称和参数的方法。
//    @Autowired注解是一个自动装配注解，用于在Spring上下文中自动连接Bean。通过使用@Autowired注解在需要依赖其他Bean对象的位置，
//    Spring会自动查找Spring容器中与此位置匹配的Bean，并注入其实例。
    private final UserRepository userRepository;
    @Autowired
    public UserServiceimp(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public User check(String userName, String password) {
        return userRepository.findUserByUserNameAndPassword(userName,password);
    }

    @Override
    public boolean isUserNameOccupied(String userName) {//是否是空对象
        return userRepository.countByUserName(userName)>0;
    }

    @Override
    public User register(User user) {
        return userRepository.save(user);
    }

    @Override
    public String getSalt(String userName) {
        //salt相当于用户id
        List<UserProjection> users = userRepository.findUserByUserName(userName);
        if(users==null||users.size()==0){
            return "";
        }
        UserProjection user = users.get(0);//获取用户的第一个对像
        if(user==null){
            return "";
        }
        String salt = user.getSalt();

        return salt==null?"":salt;
    }

    @Override
    public List<User> get() {
        return userRepository.findAllByOrderByCreateTimeDesc();
    }

    @Override
    public List<User> get(int page, int size) {
        return userRepository.findAllByOrderByCreateTimeDesc(PageRequest.of(page,size));
    }

    @Override
    public Integer count() {//统计所有用户
        return userRepository.countAllBy();
    }

    @Override
    public List<User> search(String kw) {
        return userRepository.findByQuery(kw);
    }

    @Override
    public User getById(UUID id) {
        return userRepository.findById(id).orElse(null);
    }

    //再次验证用户
    @Override
    public   ApiResult chekUesr(JSONObject json){
        String nickname = json.getString(ApiConstant.KEY_REGISTER_NICK_NAME);
        String username = json.getString(ApiConstant.KEY_REGISTER_USER_NAME);
        String password = json.getString(ApiConstant.KEY_REGISTER_PASS_WORD);
        String email = json.getString(ApiConstant.KEY_REGISTER_EMAIL);
        String phone = json.getString(ApiConstant.KEY_REGISTER_PHONE);
        String avatar = json.getString(ApiConstant.KEY_REGISTER_AVATAR);
        String salt= UUID.randomUUID().toString();
        if (StringUtils.isEmpty(nickname)){
            nickname=username;
        }
        if(StringUtils.isEmpty(username)||
                StringUtils.isEmpty(avatar)||
                StringUtils.isEmpty(phone)||
                StringUtils.isEmpty(password)){

            return new ApiResult(false, Messages.INCOMPLETE_INFO.toString(), null);
        }
        if(!StringUtils.validPhone(phone)){
            return new ApiResult(false,Messages.INVALID_FORMAT.toString(), null);
        }
        //强制提交时服务端验证
        if(isUserNameOccupied(username)){
            return new ApiResult(false,"用户已存在", null);
        }
        User user = new User();
        user.setAvatar(avatar);
        user.setEnail(email);
        user.setUserName(username);
        user.setNickName(nickname);
        user.setPassword(StringUtils.md5Encode(password,salt));//加密过的密码参数
        user.setPhone(phone);
        user.setType(User.TYPE_READER);
        user.setSalt(salt);
        VmUser vmUser = VmUser.apiLogin(register(user));
        return new ApiResult(true,"注册成功",vmUser);

    }

    @Override
    public ApiResult Login(JSONObject json){
        //json格式{“username”,"tom"，“password”}
        String userName =json.getString(ApiConstant.KEY_REGISTER_USER_NAME);  //从用户传进的
        String origin =json.getString(ApiConstant.KEY_REGISTER_PASS_WORD);
        String salt =getSalt(userName);
        User user = check(userName, StringUtils.md5Encode(origin,salt));
        if(user==null){
            return new ApiResult(false, Messages.WRONG_PASSWORD.toString(),null);
        }
        if(user.getType()<0){
            return new ApiResult(false, Messages.USER_FORBIDDEN.toString(),null);
        }
        //返回登录选项
        VmUser vm=VmUser.apiLogin(user); //有个令牌
        return new ApiResult(true, Messages.SUCCESS.toString(),vm);
    }
}
